﻿(function(exports) {
    "use strict";
    /**
     * [toArray 添加原型 返回对象包含 年、月、日、时、分、秒、天数 ]
     * @return {[type]} [description]
     */
    Date.prototype.toArray = function() {
        var now = this;
        var dateAry = Array();
        dateAry[0] = now.getFullYear();
        dateAry[1] = (now.getMonth() + 1 < 10 ? "0" : "") + (now.getMonth() + 1);
        dateAry[2] = (now.getDate() < 10 ? "0" : "") + now.getDate();
        dateAry[3] = (now.getHours() < 10 ? "0" : "") + now.getHours();
        dateAry[4] = (now.getMinutes() < 10 ? "0" : "") + now.getMinutes();
        dateAry[5] = (now.getSeconds() < 10 ? "0" : "") + now.getSeconds();
        dateAry[6] = now.getDay();
        return dateAry;
    };
    /**
     * [date 定义对象 包含 年 月 日 首先数据为当前日期]
     * @type {Object}
     */
    var date = {
            year: new Date().getFullYear(),
            month: new Date().getMonth() + 1,
            day: new Date().getDate()
        }
        /**
         * [calendar 定义日历]
         * @type {Object}
         */
    var calendar = {

        /*[init 日历初始化]
         * @param  {Function} callback [回调函数用来返回选中或者当前日期]
         * @param  {[type]}   El       [日历需要添加的位置默认追加到body]
         * @example         
         var options = {
        		El:"",
        		date:{
        			year:2016,
        			month:12,
        			day:28
        		},
        		callback:function(){        		
        		}
        	}
         */        
        init: function(options) {
            this.El = options.El || $("#clendarcontainer"); //获取日历需要放的位置元素
            this.countMonth  = options.countMonth || 2; //总共显示的月数 为 countMonth * 2 + 1
            if (options.date) {
                date = {
                    year: options.date.year,
                    month: options.date.month,
                    day: options.date.day
                }
            }
            //保留最初状态值
            this.date = {
                year: date.year,
                month: date.month,
                day: date.day
            }
            // var d={
            //     year:new Date().getFullYear(),
            //     month:new Date().getMonth()+1,
            //     day:new Date().getDate()
            // }
            this.options=options;
            this.curDate = options.curDate;
            this.renderCalendar(); //渲染日历
            this.bindEvent(options.callback); //绑定事件   
            if($('.swiper-slide-prev').find('.clendar-disabled').length == $('.swiper-slide-prev li[date-id]').length){
               $(".arrow-left").addClass('disabled');
               this.swiper.params.allowSwipeToPrev = false;
            }else{
               this.swiper.params.allowSwipeToPrev = true;
               $(".arrow-left").removeClass('disabled');
            }
            if($('.swiper-slide-next').find('.clendar-disabled').length == $('.swiper-slide-next li[date-id]').length){
               $(".arrow-right").addClass('disabled');
               this.swiper.params.allowSwipeToNext = false;
            }else{
               $(".arrow-right").removeClass('disabled');
               this.swiper.params.allowSwipeToNext = true;
            }            
        },
        /**
         * [getPointMonth 获取指定月份数据]
         */
        getPointMonth: function(obj, value) {
            var _self = this;
            var newDate = obj.year + "/" + obj.month + '/1';
            var date = new Date(new Date(newDate).setMonth(new Date(newDate).getMonth() + value));
            var maxDay = _self.getMaxDayOfMonth(date.getFullYear(), date.getMonth() + 1);
            var firstDay = _self.getFirstDay(date.getFullYear(), date.getMonth());
            return {y:date.getFullYear(),m:date.getMonth(),tm:_self.getMonthDayArray(maxDay, firstDay)};
        },
        /**
         * [getCountMonth 获取总月份]
         */
        getCountMonth: function(obj, num) {
            var _self = this;
            var newDate = obj.year + '/' + obj.month + '/1';
            var dateArray = [];
            var setDateArray = function() {
                var maxDay = _self.getMaxDayOfMonth(date.getFullYear(), date.getMonth() + 1);
                var firstDay = _self.getFirstDay(date.getFullYear(), date.getMonth());
                dateArray.push({y:date.getFullYear(),m:date.getMonth(),tm:_self.getMonthDayArray(maxDay, firstDay)});
            }
            for (var i = -num; i < 0; i++) {
                var date = new Date(new Date(newDate).setMonth(new Date(newDate).getMonth() + i));
                setDateArray();
            }
            var date = new Date(new Date(newDate).setMonth(new Date(newDate).getMonth()));
            setDateArray();
            for (var i = 1; i < num + 1; i++) {
                var date = new Date(new Date(newDate).setMonth(new Date(newDate).getMonth() + i));
                setDateArray();
            }
            //console.log(dateArray);
            return dateArray;
        },
        /**
         * [bindEvent 绑定页面事件]
         * @param  {Function} callback [回调函数]         
         */
        bindEvent: function(callback) {
            var _self = this;
            /*[日期点击事件]*/
            $(document).off('click', ".calendar-list li").on("click", ".calendar-list li", function() {
                var text = $(this).text();
                var cls=$(this).attr("class");
                date.day = text;
                if (text && cls.indexOf('clendar-disabled')==-1) {
                    callback && callback(date);
                    $(".calendar-list li").removeClass("cur");
                    $(this).addClass("cur");
                    calendar.removeCalendar();
                }
            });

            /*日历关闭*/
            $("#clendarcontainer").off('click', ".close").on("click", ".close", function() {
                calendar.removeCalendar();
            });
            /*上一个月*/
            $("#clendarcontainer").off('click', ".arrow-left").on("click", ".arrow-left", function() {
                if($(this).hasClass('disabled')){
                    _self.swiper.params.allowSwipeToPrev = false;
                }else{
                    $('.arrow-right').removeClass('disabled');
                     _self.swiper.slidePrev();
                }
                if($('.arrow-right').hasClass('disabled')){
                    _self.swiper.params.allowSwipeToNext = false;
                }else{
                    _self.swiper.params.allowSwipeToNext = true;
                }
            });
            /*下一个月*/
            $("#clendarcontainer").off('click', ".arrow-right").on("click", ".arrow-right", function() {
                if($(this).hasClass('disabled')){
                    _self.swiper.params.allowSwipeToNext = false;
                }else{
                    $('.arrow-left').removeClass('disabled');
                    _self.swiper.slideNext();
                }
                if($('.arrow-left').hasClass('disabled')){
                    _self.swiper.params.allowSwipeToPrev = false;
                }else{
                    _self.swiper.params.allowSwipeToPrev = true;
                }
            });                        
            /*关闭遮照*/
            $("#clendarcontainer").off('click', '#calendarMask').on('click', '#calendarMask', function() {
                _self.removeCalendar();
            });
        },
        /**
         * [addZero 不满10加0]
         * @param {[type]} str [字符串]
         */
        addZero:function(str){
            var month= Number(str);
            if(month<10){
                month='0'+month;
            }
            return month;
        },
        /**
         * [getDate 判断日期 获取当前选择中的日期创建日历]
         * @param  {[type]} obj [description]
         * @return {[type]}     [description]
         */
        getDate: function(val) {
            var _self = this;
            if (val > 0) {
                if (date.month == 1) {
                    date.month = 12;
                    date.year--;
                } else {
                    date.month--;
                }
            } else {
                if (date.month == 12) {
                    date.month = 1;
                    date.year++;
                } else {
                    date.month++;
                }
            }
            date.month = _self.addZero(date.month);
            $(".calendar-txt").text(date.year + "年" + date.month + "月");
            //_self.setToday();
        },
        /**
         * [setToday 设置今天日期]
         */
        setToday: function() {
            var _self = this;
            /*if (new Date().getFullYear() == date.year && (new Date().getMonth() + 1) == date.month && new Date().getDate() == date.day) {
                $('.swiper-slide-active [date-id="' + new Date().getDate() + '"]').addClass("day");
            }*/
            if (_self.curDate.year + "" + (_self.curDate.month) == date.year + "" + date.month) {
                $('.swiper-slide-active [date-id="' +parseInt(_self.curDate.day) + '"]').addClass("cur");
            }
        },
        /**
         * [removeCalendar 删除日历]
         * @return {[type]} [description]
         */
        removeCalendar: function() {
            $("#calendarContent").slideUp(0, function() {
                $("#calendar").remove();
            });
        },
        /**
         * [getMonthDayArray 日历数据处理]
         * @return {[type]} [description]
         */
        getMonthDayArray: function(maxDay, firstDay) {
            var currentMonthDay = [];
            for (var i = maxDay; i > 0; i--) {
                currentMonthDay.push(i);
            }
            for (var i = firstDay; i > 0; i--) {
                currentMonthDay.push("");
            }
            currentMonthDay = currentMonthDay.reverse();
            for (var i = 7 - currentMonthDay.length % 7; i > 0 && i < 7; i--) {
                currentMonthDay.push("");
            }            
            return currentMonthDay;
        },
        /*创建每个月的日历*/
        createSlide: function(array) {
            //console.log(array);
            var _self = this;
            var html = "";
            html += '<div class="calendar-list swiper-slide">';
            array.tm.forEach(function(e, index) {                
                if (index % 7 == 0) {
                    html += '<ul>';
                }
                if (e) {
                    //console.log(array.y,array.m)
                    var cdate=new Date(array.y,array.m,e,0,0,0).getTime();
                    var cls='';                    
                    if(_self.options.min && _self.options.max){
                        if(cdate>=_self.options.min && cdate<=_self.options.max){

                        }else{
                            cls='clendar-disabled';
                        }
                    }
                    
                    html += '<li date-id="' + e + '" class='+cls+'>' + e + '</li>';
                } else {
                    html += '<li></li>';
                }
                if ((index + 1) % 7 == 0) {
                    html += '</ul>';
                }
            });
            html += '</div>';
            return html;
        },
        /**
         * [renderCalendar 渲染日历]
         * @return {[type]} [description]
         */
        renderCalendar: function() {
            var _self = this;
            //console.log(1,date);
            var monthArray = this.getCountMonth(date, this.countMonth);
            var htmlWrap = '<div id="calendar" class="calendar"><div id="calendarMask"></div><div id="calendarContent"><div id="calendarContentMask"></div>';
            htmlWrap += '<div class="bar expend">';
            htmlWrap += '<span class="arrow-left"></span>';
            htmlWrap += '<span class="calendar-txt">' + date.year + "年" + date.month + "月" + '</span>';
            htmlWrap += '<span class="arrow-right"></span>';
            htmlWrap += '<span class="close"></span>';
            htmlWrap += '</div>';
            htmlWrap += '<div class="calendar-wrap">';
            htmlWrap += '<ul class="calendar-bar">';
            htmlWrap += '<li>周日</li>';
            htmlWrap += '<li>周一</li>';
            htmlWrap += '<li>周二</li>';
            htmlWrap += '<li>周三</li>';
            htmlWrap += '<li>周四</li>';
            htmlWrap += '<li>周五</li>';
            htmlWrap += '<li>周六</li>';
            htmlWrap += '</ul>';
            htmlWrap += '<div class="calendar-list-wrap">';
            htmlWrap += '<div class="swiper-container">';
            htmlWrap += '<div class="swiper-wrapper">';

            monthArray.forEach(function(newMonthArray, i) {
                htmlWrap += _self.createSlide(newMonthArray);
            });
            htmlWrap += '</div>';
            htmlWrap += '</div>';
            htmlWrap += '</div></div>';
            htmlWrap += '</div>';
            htmlWrap += '</div>';
            $("#calendar").length == 0 && this.El.append(htmlWrap);
            this.swiper = new Swiper('.swiper-container', {
                pagination: '.swiper-pagination',
                onInit: function(swiper) {
                    swiper.slideTo(_self.countMonth, 0, 0);
                    if(!_self.options.startEmpty){
                        _self.setToday();
                    }
                },
                onSlideChangeStart: function(swiper){
      				$("#calendarContentMask").show();
      				setTimeout(function(){
						$("#calendarContentMask").hide();
      				}, 500);
    			},
                onSlideNextEnd: function(swiper) {
                    $('.arrow-left').removeClass('disabled');
                    if($('.arrow-right').hasClass('disabled')){
                        swiper.params.allowSwipeToNext = false;
                        return;
                    }else{
                        swiper.params.allowSwipeToPrev = true;
                        if($('.swiper-slide-active').find('.clendar-disabled').length != 0){
                            swiper.params.allowSwipeToNext = false;
                            $('.arrow-right').addClass('disabled');
                        }else{
                            swiper.params.allowSwipeToNext = true;
                            $('.arrow-right').removeClass('disabled');
                        }
                         _self.getDate(0);
                        if (swiper.activeIndex == _self.countMonth*2) {
                            swiper.removeSlide(0);
                            swiper.appendSlide(_self.createSlide(_self.getPointMonth(date, 1)));
                        }
                    }
                },
                onSlidePrevEnd: function(swiper) {
                    $('.arrow-right').removeClass('disabled');
                    if($('.arrow-left').hasClass('disabled')){
                        swiper.params.allowSwipeToPrev = false;
                        return;
                    }else{
                        swiper.params.allowSwipeToNext = true;
                        if($('.swiper-slide-active').find('.clendar-disabled').length != 0){
                            swiper.params.allowSwipeToPrev = false;
                            $('.arrow-left').addClass('disabled');
                        }else{
                            swiper.params.allowSwipeToPrev = true;
                            $('.arrow-left').removeClass('disabled');
                        }
                         _self.getDate(1);
                        if (swiper.activeIndex == 0) {
                            swiper.removeSlide(_self.countMonth*2);
                            swiper.prependSlide(_self.createSlide(_self.getPointMonth(date, -1)));
                        }
                    }
                }
            });
        },
        /**
         * 当月最大天数
         */
        getMaxDayOfMonth: function(iYear, iMonth) {
            var newDate = new Date(iYear, iMonth, 0);
            var dateAry = newDate.toArray();
            return parseInt(dateAry[2]);
        },
        /**
         * 当月第一天是周几
         */
        getFirstDay: function(iYear, iMonth) {
            var newDate = new Date(iYear, iMonth, 1);
            var dateAry = newDate.toArray();
            return parseInt(dateAry[6]);
        }
    }
    exports.calendar = calendar;
    /**
     * 兼容AMD和非AMD规范
     */
    if (typeof define === "function" && define.amd) {
        define(["jquery", "swiper"], function($, swiper) {
            return calendar;
        });
    }
})(window);
